package com.zcx.base.redis.lock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangcx
 */
@Component
@Slf4j
public class KeyRedisLock {

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 锁对应的值，无意义，写为1
     */
    private static final String value = "1";

    public boolean lock(String key, long releaseTime) {
        // 尝试获取锁
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
        // 判断结果
        boolean lock = boo != null && boo;

        if (lock) {
            log.info("获取锁成功");
        } else {
            log.info("获取锁失败");
        }
        return lock;
    }

    public boolean tryLock(String key, long releaseTime, long blockTime) {
        // 尝试获取锁
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
        // 判断结果
        if (!boo) {
            int time = 0;
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
                if (boo) {
                    log.info("获取锁成功");
                    break;
                }
                if (time> (blockTime * 1000)) {
                    log.info("超过指定时间，获取锁失败");
                    break;
                }
                time += 100;
            }
        } else {
            log.info("获取锁成功");
        }
        return boo != null && boo;
    }

    public void unlock(String key) {
        // 删除key即可释放锁
        redisTemplate.delete(key);
    }
}